<template>
	<view class="container">
		<image class="canvas_img" :src="canvasUrl" mode="" v-if="canvasUrl&&popVisible"></image>
		<u-popup mode="bottom" round="32" :show="popVisible" @close="handleColse">
			<view class="content">
				<view class="title fc fz_16">
					分享
				</view>
				<view class="select_wrap fx aic jcb">
					<!-- <view class="select_item fc_666 fx fx_col aic" @click="handleClick('command')" v-if="type!='goods'">
						<view class="fx aic jcc width_52 height_52 br_12 bc_fa mb_8">
							<image src="@/static/images/qrcode_ico_share_kouling.png" mode=""></image>
						</view>
						<text class="name">
							复制口令
						</text>
					</view> -->
					<button class="block_btn select_item fc_666 fx fx_col aic" open-type="share"
						@click="handleClick('url')">
						<view class="fx aic jcc width_52 height_52 br_12 bc_fa mb_8">
							<image src="@/static/images/qrcode_ico_share_wechat.png" mode=""></image>
						</view>
						<text class="name">
							微信
						</text>
					</button>
					<button class="block_btn select_item fc_666 fx fx_col aic" @click="handleClick('circle')">
						<view class="fx aic jcc width_52 height_52 br_12 bc_fa mb_8">
							<image src="@/static/images/qrcode_ico_share_friends.png" mode=""></image>
						</view>
						<text class="name">
							朋友圈
						</text>
					</button>
					<button class="block_btn select_item fc_666 fx fx_col aic" @click="handleClick('download')"
						v-if="type=='goods'">
						<view class="fx aic jcc width_52 height_52 br_12 bc_fa mb_8">
							<image src="@/static/images/qrcode_ico_share_qq.png" mode=""></image>
						</view>
						<text class="name">
							保存到本地
						</text>
					</button>
				</view>
				<button class="btn" @click="handleColse">取消分享</button>
			</view>
		</u-popup>
		<view class="pf t_0 l_0 b_0 r_0" style="background: rgba(0,0,0,0.65);z-index: 10000"
			v-if="popVisible&&guideVisible" @click="guideVisible=false">
			<image class="width_120 height_120" style="padding-left:414rpx" src="@/static/images/share_line.png"
				mode="">
			</image>
			<view class="fb fz_16 fc_fff" style="padding-left:240rpx">
				<view>
					1、点击右上角“··· ”
				</view>
				<view class="mt_8 fx aic">
					<text>2、点击</text>
					<image class="width_44 height_44 plr_7" src="@/static/images/share_timeline.png"></image>
					<text>分享到朋友圈</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import canvasUtils from '@/utils/canvas'
	import api from '@/service/config/api.js'
	import base64src from '@/utils/base64src.js'
	import {
		mapState
	} from 'vuex'
	export default {
		props: {
			visible: {
				default: false,
				type: Boolean
			},
			data: {
				default: () => ({}),
				type: Object
			},
			params: {
				default: () => ({}),
				type: Object
			},
			type: {
				default: '',
				type: String
			},
			goodsType: {
				default: 1,
				type: Number
			},
			page: {
				default: '',
				type: String
			}
		},
		watch: {
			visible: {
				handler(newVal) {
					this.popVisible = newVal;
					if (newVal && this.data) {
						this.userInfo = this.$storage.getItem('basicUnserInfo') || {}
						console.log('待分享数据', this.data)
						//TODO 测试环境不能生成二维码 暂时不生成
						// canvasUtils.PosterCanvas([
						// 	this.$utils.getStaticUrl(this.data.coverImageUrl || this.data.specificationImageUrl),
						// 	this.$utils.getStaticUrl(this.data.coverImageUrl || this.data.specificationImageUrl)
						// ], this.data.productName||this.data.name, this.getSalePrice(), this.devicePixelRatio).then(
						// 	res1 => {
						// 		this.canvasUrl = res1
						// 	})
						// TODO 生产环境
						let paramsUrl = `${this.params.id||''}$${this.params.customerId||''}$${this.params.goodsType||''}`
						const params = {
							g: paramsUrl
						}
						console.log('params-----',params)
						api.post('/user/api/auth/getWechatQrCode', {
							params: params,
							page: this.page ? this.page.slice(1) : this.type == 'goods' ? 'pages/goods/pages/detail' : this
								.page.slice(1),
							width: 280
						}).then(res => {
							if (res.data) {
								base64src(res.data).then(path => {
									canvasUtils.PosterCanvas([
											this.$utils.getStaticUrl(this.data.coverImageUrl || this.data.specificationImageUrl),
											path
										], this.data.productName||this.data.name||'', this.data.salePrice||'', this
										.devicePixelRatio).then(
										res1 => {
											this.canvasUrl = res1
										})
								})
							}
						}).catch(() => {
							this.$utils.showToast('图片生成失败')
						})

					}
					if (!newVal) {
						this.guideVisible = false
						this.canvasUrl = ''
					}
				},
				immediate: true
			},
		},
		data() {
			return {
				popVisible: false,
				canvasUrl: '',
				devicePixelRatio: 1,
				guideVisible: false,
				userInfo: this.$storage.getItem('basicUnserInfo') || {},
			}
		},
		computed: {
			...mapState(['appType']),
			checkToken() {
				return !!this.$storage.getItem('token')
			},
		},
		created() {
			uni.getSystemInfo({
				success: (res) => {
					this.devicePixelRatio = res.devicePixelRatio
				}
			})
		},
		methods: {
			getSalePrice() {
				if (this.goodsType == 3) {
					return this.data.bargainirgMinPrice || 0
				}
				return this.$store.state.appType === this.$base.USER_TYPE ? (this.data.salePrice || 0) : (this.data
					.wholesalePrice ||
					this.data.salePrice || 0)
			},
			handleColse() {
				this.$emit('update:visible', false)
			},
			handleClick(type) {
				console.log('this.params',this.params)
				if(this.checkToken) {
					api.post('/goods/api/product/addShareStatistics', {
						productId: this.params.goodsId ? this.params.goodsId : this.params.id,
						...this.$store.state.userInfo.customerId ? {
							customerId: this.$store.state.userInfo.customerId
						} : {},
						userType: this.userInfo.identityType || 1
					}, {
						noHideLoading: false,
						noToast: false
					})
				}
				if (type == 'download') {
					if (!this.canvasUrl) {
						this.$utlis.showToast('图片保存失败')
						return
					}
					var that = this
					uni.getSetting({
						success(res) {
							if (res.authSetting['scope.writePhotosAlbum']) {
								// 已经获得授权，直接存储
								that.saveImg();
							} else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
								// 第一次运行，授权未定义，可以直接保存，系统会一次性询问用户权限
								that.saveImg();
							} else {
								// 用户拒绝授权后，打开设置页可以看到授权提示开关
								uni.openSetting({
									success(res) { // 用户授权
										if (res.authSetting['scope.writePhotosAlbum']) {
											that.saveImg();
										} else { // 用户拒绝授权
											that.setData({
												displayLoading: "none"
											})
											that.$utils.showToast('权限不足')
										}
									},
									fail(res) {
										that.setData({
											displayLoading: "none"
										})
										that.$utils.showToast('设置失败')
									}
								})
							}
						},
						fail(res) {
							console.log(res)
							that.setData({
								displayLoading: "none"
							})
							that.$utils.showToast('设置失败')
						}
					})
					return
				}
				if (type == 'command') {
					const paramsCopy = JSON.parse(JSON.stringify(this.params))
					delete paramsCopy.goodsId
					let path = (this.page ? this.page : this.type == 'goods' ? 'pages/goods/pages/detail' : this
						.page) + uni.$u.queryParams({
						...paramsCopy,
						app: this.$store.state.platformInfo.id,
						shareType: 'command'
					})
					console.log('path----',path,this.$store.state.platformInfo.id)
					uni.setClipboardData({
						data: encodeURIComponent(path), // data的值为你要复制的内容
						success: res => {
							uni.showToast({
								title: '口令复制成功'
							})
						}
					});
				}
				if (type == 'circle') {
					this.guideVisible = true
					return
				}
				this.$emit('select', type)
				this.$emit('update:visible', false)
			},
			saveImg() {
				uni.saveImageToPhotosAlbum({
					filePath: this.canvasUrl,
					success: (data) => {
						this.$emit('select', 'download')
						uni.hideLoading();
						uni.showToast({
							title: '已保存至相册！',
							icon: 'success',
							duration: 2000
						})
					},
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		/deep/.u-popup__content__close {
			top: 38rpx;
			right: 38rpx;

			.u-icon {
				font-size: 28rpx !important;
				background: #999999;
			}
		}

		.content {
			box-sizing: border-box;
			padding: 32rpx 36rpx;
		}

		.title {
			text-align: center;
		}

		.select_wrap {
			margin-top: 32rpx;
			padding: 0 48rpx;

			image {
				width: 64rpx;
				height: 64rpx;
			}
		}

		.btn {
			margin: 48rpx 16rpx 16rpx;
			line-height: 72rpx;
			border-radius: 134rpx;
			color: #333;
			font-size: 28rpx;
			background: #F7F7F8;
			border: none;

			&::after {
				border: none;
			}
		}

		.canvas_img {
			position: fixed;
			top: 96rpx;
			left: 0;
			right: 0;
			margin: 0 auto;
			width: 600rpx;
			height: 718rpx;
			z-index: 11000;
		}
	}
</style>